using Gateway.Common.Enums;
using Gateway.IApplication.UserMessage;
using Gateway.Infrastructure.Provider.Operator;
using Gateway.IQuery.UserMessage;
using Gateway.IQuery.UserMessage.Result;
using Aurora.SingalR.Hubs;
using Aurora.TaskScheduler.Extension;
using Gateway.UI.Api.TaskJobs;

namespace Gateway.UI.Api.Controllers;

/// <summary>
/// 用户消息
/// </summary>
public class UserMessageController : BaseController
{
    private readonly IOperatorProvider _operatorProvider;
    private readonly IUserMessageQuery _userMessageQuery;
    private readonly IUserMessageApp _userMessageApp;
    private readonly HubHandlerProvider _hubHandlerProvider;
    private readonly TaskJobUtil _taskJobUtil;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="operatorProvider"></param>
    /// <param name="userMessageQuery"></param>
    /// <param name="userMessageApp"></param>
    /// <param name="hubHandlerProvider"></param>
    /// <param name="taskJobUtil"></param>
    public UserMessageController(IOperatorProvider operatorProvider, IUserMessageQuery userMessageQuery,
        IUserMessageApp userMessageApp, HubHandlerProvider hubHandlerProvider, TaskJobUtil taskJobUtil)
    {
        _operatorProvider = operatorProvider;
        _userMessageQuery = userMessageQuery;
        _userMessageApp = userMessageApp;
        _hubHandlerProvider = hubHandlerProvider;
        _taskJobUtil = taskJobUtil;
    }


    /// <summary>
    /// 获取未读消息
    /// </summary>
    /// <returns></returns>
    [HttpGet, Route("all/noread")]
    public async Task<List<UserMessageDetailResult>> GetAllNoRead(int size = 10)
    {
        return await _userMessageQuery.GetAllNoRead(_operatorProvider.GetOperator().OperatorId, size);
    }

    /// <summary>
    /// 阅读消息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet, Route("read/{id}")]
    public async Task<bool> Read([FromRoute] string id)
    {
        return await _userMessageApp.Read(id);
    }

    /// <summary>
    /// 阅读消息
    /// </summary>
    /// <returns></returns>
    [HttpGet, Route("read/all")]
    public Task<bool> ReadAll()
    {
        _taskJobUtil.InvokeLater(typeof(UserReadAllMessageJob), _operatorProvider.GetOperator().OperatorId);
        return Task.FromResult(true);
    }

    /// <summary>
    /// push 消息
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    [HttpPost, Route("push")]
    public async Task<bool> Push(HubMessage message)
    {
        await _hubHandlerProvider.Send(new HubMessage()
        {
            Creator = _operatorProvider.GetOperator().OperatorId,
            User = _operatorProvider.GetOperator().OperatorId,
            Message = message.Message,
            Type = SendTypeEnum.Person.Value
        });
        return true;
    }
}